//
//  SAShoppingCartView.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/5/20.
//

#import "SAShoppingCartView.h"
#import "SASalesOrderViewListModel.h"
#import "SAShoppingCartHeaderView.h"
#import "SAShoppingCartCell.h"
#import "YBImageBrowser.h"

@interface SAShoppingCartView ()<UITableViewDelegate, UITableViewDataSource, YBImageBrowserDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) NSArray *imageList;

@end

@implementation SAShoppingCartView

-(instancetype)initWith:(NSMutableArray<SASalesOrderViewListModel *> *) marr {
    if (self = [super init]) {
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kScaleNum(50) - SafeFooterHeight);
        self.backgroundColor = kColor(0, 0, 0, 0.3);
        self.userInteractionEnabled = YES;
        self.dataMarr = marr;
        for (SASalesOrderViewListModel *model in self.dataMarr) {
            model.targetSkuList = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                if ([list.stock floatValue] != 0) {
                    [model.targetSkuList addObject:list];
                }
            }
        }
        [self initUI];
    }
    return self;
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr[section].targetSkuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SAShoppingCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAShoppingCartCell" forIndexPath:indexPath];
    cell.isNegative = self.isNegative;
    cell.isWarehousingStock = self.isWarehousingStock;
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].targetSkuList[indexPath.row];
    cell.skuModel = model;
    
    __weak typeof(self) weakSelf = self;
    cell.inputBlock = ^(NSString * _Nonnull str) {
        if ([str integerValue] > [model.inventoryCount integerValue]) {
            model.stock = model.inventoryCount;
        }else {
            model.stock = str;
        }
        !weakSelf.refreshBlock ?: weakSelf.refreshBlock();
    };

    cell.addBlock = ^{
        if (self.isNegative == YES) {
            if ([model.stock integerValue] + 1 > [model.inventoryCount integerValue]) {
                if ([model.inventoryCount integerValue] >= 0) {
                    model.stock = model.inventoryCount;
                }else {
                    model.stock = @"0";
                }
                [Prompt popPromptViewWithMsg:[NSString stringWithFormat:@"库存不足,当前库存%@件",model.inventoryCount] duration:2];
            }else {
                model.stock = [NSString stringWithFormat:@"%zd",[model.stock integerValue] + 1];
            }
        }else {
            model.stock = [NSString stringWithFormat:@"%zd",[model.stock integerValue] + 1];
        }
        !weakSelf.refreshBlock ?: weakSelf.refreshBlock();
    };

    cell.cutBlock = ^{
        if (weakSelf.isWarehousingStock != YES) {
            model.stock = [NSString stringWithFormat:@"%zd",[model.stock integerValue] - 1];
            if ([model.stock integerValue]< 0) {
                model.stock = @"0";
            }
        }else {
            model.stock = [NSString stringWithFormat:@"%zd",[model.stock integerValue] - 1];
        }
        !weakSelf.refreshBlock ?: weakSelf.refreshBlock();
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(40);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    SAShoppingCartHeaderView *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAShoppingCartHeaderView"];
    SASalesOrderViewListModel *model = self.dataMarr[section];
    header.model = model;
    WeakSelf
    header.deleteBlock = ^{
        for (SASalesOrderToPendSkuList *list in model.targetSkuList) {
            list.stock = @"0";
        }
        !weakSelf.refreshBlock ?: weakSelf.refreshBlock();
        [weakSelf.dataMarr removeObject:model];
        if (weakSelf.dataMarr.count > 0) {
            [tableView reloadData];
        }else {
            [weakSelf clickedDeleteBtn];
        }
    };
    
    header.showImageBlock = ^{
        [weakSelf showImage:model.imgList];
    };
    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(71);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return kScaleNum(1);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SASalesOrderViewListModel *headerModel = self.dataMarr[indexPath.section];
    SASalesOrderToPendSkuList *model = self.dataMarr[indexPath.section].targetSkuList[indexPath.row];
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        model.stock = @"0";
        if (headerModel.targetSkuList.count == 1) {
            [weakSelf.dataMarr removeObject:headerModel];
        }else {
            [headerModel.targetSkuList removeObject:model];
        }
        !weakSelf.refreshBlock ?: weakSelf.refreshBlock();
        if (weakSelf.dataMarr.count > 0) {
            [tableView reloadData];
        }else {
            [weakSelf clickedDeleteBtn];
        }
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - event
-(void)clickedDeleteBtn {
    
    NSMutableArray<SASalesOrderViewListModel *> *marr = [NSMutableArray array];
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        BOOL isZero = YES;
        for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
            if ([list.stock integerValue] != 0) {
                isZero = NO;
            }
        }
        if (isZero == NO) {
            [marr addObject:model];
        }
    }
    !self.refreshMarrBlock ?: self.refreshMarrBlock(marr);

    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}
 

#pragma mark - initUI
-(void)initUI {
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = SARectMake(0, 0, kBaseScreenWidth ,278);
    [deleteBtn addTarget:self action:@selector(clickedDeleteBtn) forControlEvents:UIControlEventTouchUpInside];
    deleteBtn.userInteractionEnabled = YES;
    [self addSubview:deleteBtn];
    
    [self addSubview:self.tableView];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(278), kScreenWidth, kScreenHeight - kScaleNum(328) - SafeFooterHeight) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAShoppingCartHeaderView class] forHeaderFooterViewReuseIdentifier:@"SAShoppingCartHeaderView"];
        [_tableView registerClass:[SAShoppingCartCell class] forCellReuseIdentifier:@"SAShoppingCartCell"];
    }
    return _tableView;
}

@end
